<script lang="ts" setup>
import type { NovelCategory } from '@/api/types/novel'
import { onMounted, ref } from 'vue'
import { addFavorite, getNovelCategories, getPopularNovels, getRecommendedNovels } from '@/api/novel'
import { safeAreaInsets } from '@/utils/systemInfo'

defineOptions({
  name: 'Home',
})
definePage({
  type: 'home',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '小说分享',
  },
})

// 轮播图数据（从API获取的推荐小说）
const banners = ref<any[]>([])

// 分类导航数据（从API获取）
const categories = ref<any[]>([])

// 编辑推荐数据（从API获取）
const editorRecommendations = ref<any[]>([])

// 热门推荐数据（从API获取）
const hotNovels = ref<any[]>([])

// 加载状态
const loading = ref(false)

// 页面加载时获取数据
onMounted(async () => {
  await loadHomeData()
})

// 加载首页数据
async function loadHomeData() {
  try {
    loading.value = true

    // 并行加载所有数据
    await Promise.all([
      loadCategories(),
      loadEditorRecommendations(),
      loadHotNovels(),
    ])
    // 设置轮播图（使用推荐小说的前几个）
    banners.value = editorRecommendations.value.slice(0, 3).map(novel => ({
      id: novel.id,
      image: novel.cover || `https://picsum.photos/seed/novel${novel.id}/400/200.jpg`,
      title: novel.title,
      description: `${novel.description?.substring(0, 50)}...` || '精彩小说，值得一读',
    }))
  }
  catch (error) {
    console.error('加载首页数据失败:', error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'error',
    })
  }
  finally {
    loading.value = false
  }
}

// 加载分类数据
async function loadCategories() {
  try {
    const response = await getNovelCategories()

    // 数据库分类ID映射关系
    // 1->玄幻 2->奇幻 3->仙侠 4->武侠 5->都市 6->历史 7->军事 8->科幻
    // 9->游戏 10->体育 11->悬疑 12->轻小说 13->言情 14->同人 15->种田 16->脑洞
    const iconMap: { [key: string]: string } = {
      热门: 'fas fa-fire',
      言情: 'fas fa-heart',
      玄幻: 'fas fa-dragon',
      奇幻: 'fas fa-hat-wizard',
      仙侠: 'fas fa-yin-yang',
      武侠: 'fas fa-fist-raised',
      都市: 'fas fa-city',
      历史: 'fas fa-landmark',
      军事: 'fas fa-shield-alt',
      科幻: 'fas fa-rocket',
      游戏: 'fas fa-gamepad',
      体育: 'fas fa-running',
      悬疑: 'fas fa-ghost',
      轻小说: 'fas fa-feather',
      同人: 'fas fa-users',
      种田: 'fas fa-seedling',
      脑洞: 'fas fa-brain',
    }

    categories.value = [
      { id: 0, name: '热门', icon: 'fas fa-fire' },
      ...response.map((category: NovelCategory) => ({
        id: category.id,
        name: category.name,
        icon: iconMap[category.name] || 'fas fa-book',
      })),
    ]
  }
  catch (error) {
    console.error('加载分类失败:', error)
    uni.showToast({
      title: '分类加载失败',
      icon: 'error',
    })
  }
}

// 加载编辑推荐
async function loadEditorRecommendations() {
  try {
    const response = await getRecommendedNovels({ limit: 6 })

    editorRecommendations.value = response.map(novel => ({
      id: novel.id,
      title: novel.title,
      author: novel.author,
      cover: novel.coverImage || `https://picsum.photos/seed/cover${novel.id}/80/120.jpg`,
      description: novel.description,
      viewCount: novel.readCount,
      likeCount: novel.favoriteCount,
      bookmarkCount: Math.floor(novel.favoriteCount * 0.7), // 估算数据
    }))
  }
  catch (error) {
    console.error('加载编辑推荐失败:', error)
    uni.showToast({
      title: '推荐加载失败',
      icon: 'error',
    })
  }
}

// 加载热门推荐
async function loadHotNovels() {
  try {
    const response = await getPopularNovels({ limit: 6 })

    hotNovels.value = response.map(novel => ({
      id: novel.id,
      title: novel.title,
      cover: novel.coverImage || `https://picsum.photos/seed/hot${novel.id}/150/200.jpg`,
    }))
  }
  catch (error) {
    console.error('加载热门推荐失败:', error)
    uni.showToast({
      title: '热门加载失败',
      icon: 'error',
    })
  }
}

// 当前轮播图索引
const currentBannerIndex = ref(0)

// 轮播图切换
function handleBannerChange(e: any) {
  currentBannerIndex.value = e.detail.current
}

// 点击轮播图
function handleBannerClick(banner: any) {
  uni.navigateTo({
    url: banner.link,
  })
}

// 点击分类
function handleCategoryClick(category: any) {
  uni.navigateTo({
    url: `/pages/search/index?category=${category.name}`,
  })
}

// 点击小说卡片
function handleNovelClick(novel: any) {
  uni.navigateTo({
    url: `/pages/novel-detail/index?id=${novel.id}`,
  })
}

// 处理小说操作 (收藏)
async function handleNovelAction(novel: any) {
  try {
    if (novel.isInLibrary) {
      // 从书架移除
      // TODO: 实现取消收藏功能
      uni.showToast({
        title: '已从书架移除',
        icon: 'success',
      })
    }
    else {
      // 添加到书架
      await addFavorite({ novelId: novel.id })
      novel.isInLibrary = true
      uni.showToast({
        title: '已加入书架',
        icon: 'success',
      })
    }
  }
  catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'error',
    })
  }
}

// 处理搜索
function handleSearch(e: any) {
  const searchText = e.detail.value.trim()
  if (searchText) {
    uni.navigateTo({
      url: `/pages/search/index?q=${encodeURIComponent(searchText)}`,
    })
  }
}

// 处理轮播图指示器点击
function handleDotClick(index: number) {
  currentBannerIndex.value = index
}

// 处理更多推荐
function handleMoreRecommendations() {
  uni.navigateTo({
    url: '/pages/discover/index?type=editor',
  })
}

// 处理更多热门
function handleMoreHot() {
  uni.navigateTo({
    url: '/pages/discover/index?type=hot',
  })
}

// 格式化数量显示
function formatCount(count: number) {
  if (count >= 10000) {
    return `${(count / 10000).toFixed(1)}万`
  }
  if (count >= 1000) {
    return `${(count / 1000).toFixed(1)}k`
  }
  return count.toString()
}
</script>

<template>
  <view class="home-page bg-bg-dark" :style="{ paddingTop: `${safeAreaInsets?.top}px` }">
    <!-- 顶部搜索栏 -->

    <!-- 主要内容区域 -->
    <view class="">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 搜索框 -->
      <view v-else class="search-container">
        <i class="fas fa-search search-icon" />
        <input
          type="text"
          class="search-input"
          placeholder="搜索小说、作者或用户"
          @confirm="handleSearch"
        >
      </view>

      <!-- 内容区域 (非加载状态) -->
      <template v-if="!loading">
        <!-- 轮播推荐 -->
        <section class="carousel-container">
          <swiper
            class="carousel-swiper"
            :indicator-dots="false"
            :autoplay="true"
            :interval="3000"
            :duration="500"
            @change="handleBannerChange"
          >
            <swiper-item
              v-for="(banner, index) in banners"
              :key="banner.id"
              @click="handleNovelClick(banner)"
            >
              <view class="carousel-slide" :class="{ active: currentBannerIndex === index }">
                <image :src="banner.image" class="carousel-image" mode="aspectFill" />
                <view class="carousel-overlay">
                  <view class="carousel-title">
                    {{ banner.title }}
                  </view>
                  <view class="carousel-description">
                    {{ banner.description }}
                  </view>
                </view>
              </view>
            </swiper-item>
          </swiper>

          <!-- 轮播指示器 -->
          <view class="carousel-dots">
            <view
              v-for="(_, index) in banners"
              :key="index"
              class="carousel-dot"
              :class="{ active: currentBannerIndex === index }"
              @click="handleDotClick(index)"
            />
          </view>
        </section>

        <!-- 分类导航 -->
        <section class="category-nav">
          <view
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            @click="handleCategoryClick(category)"
          >
            <view class="category-icon">
              <i :class="category.icon" class="category-icon-fa" />
            </view>
            <text class="category-name">{{ category.name }}</text>
          </view>
        </section>

        <!-- 编辑推荐 -->
        <section class="recommendation-section">
          <view class="section-header">
            <text class="section-title">编辑推荐</text>
            <view class="more-link" @click="handleMoreRecommendations">
              <text class="more-text">更多</text>
              <i class="fas fa-chevron-right" />
            </view>
          </view>
          <view class="novel-cards">
            <view
              v-for="novel in editorRecommendations"
              :key="novel.id"
              class="novel-card"
              @click="handleNovelClick(novel)"
            >
              <image :src="novel.cover" class="novel-cover" mode="aspectFill" />
              <view class="novel-info">
                <view class="novel-main-info">
                  <text class="novel-title">{{ novel.title }}</text>
                  <text class="novel-author">作者：{{ novel.author }}</text>
                  <text class="novel-description">{{ novel.description }}</text>
                </view>
                <view class="novel-meta">
                  <view class="meta-item">
                    <i class="fas fa-eye" />
                    <text class="meta-text">{{ formatCount(novel.viewCount) }}</text>
                  </view>
                  <view class="meta-item">
                    <i class="fas fa-heart" />
                    <text class="meta-text">{{ formatCount(novel.likeCount) }}</text>
                  </view>
                  <view class="meta-item">
                    <i class="fas fa-bookmark" />
                    <text class="meta-text">{{ formatCount(novel.bookmarkCount) }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </section>

        <!-- 热门推荐 -->
        <section class="hot-section">
          <view class="section-header">
            <text class="section-title">热门推荐</text>
            <view class="more-link" @click="handleMoreHot">
              <text class="more-text">更多</text>
              <i class="fas fa-chevron-right" />
            </view>
          </view>
          <view class="novel-grid">
            <view
              v-for="novel in hotNovels"
              :key="novel.id"
              class="novel-grid-item"
              @click="handleNovelClick(novel)"
            >
              <image :src="novel.cover" class="novel-grid-cover" mode="aspectFill" />
              <text class="novel-grid-title">{{ novel.title }}</text>
            </view>
          </view>
        </section>
      </template>
    </view>

    <!-- 底部间距 -->
    <view class="bottom-spacing" />
  </view>
</template>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  /* padding-bottom: 120rpx; // 为底部导航留出空间 */
}

// 顶部搜索栏样式
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-md);
  background-color: var(--background-medium);
}

.header-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.app-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.header-right {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

// 搜索框样式
.search-container {
  position: relative;
  margin: 0 var(--spacing-md) var(--spacing-md);
  margin-top: 12rpx;
  padding: var(--spacing-sm);
  background-color: var(--background-light);
  border-radius: var(--border-radius);
  display: flex;
  align-items: center;
}

.search-icon {
  color: var(--text-muted);
  margin-right: var(--spacing-sm);
}

.search-input {
  flex: 1;
  font-size: var(--font-size-md);
  color: var(--text-primary);
  background: transparent;
  outline: none;
}

.search-input::placeholder {
  color: var(--text-muted);
}

// 轮播图样式（与UI原型一致）
.carousel-container {
  position: relative;
  width: calc(100% - 64rpx); // 使用rpx计算，相当于减去2个32rpx的margin
  height: 400rpx; // 200px转换为rpx
  border-radius: var(--border-radius);
  overflow: hidden;
  margin: 0 32rpx 48rpx; // 使用rpx单位
}

.carousel-swiper {
  width: 100%;
  height: 100%;
}

.carousel-slide {
  position: relative;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.carousel-slide.active {
  opacity: 1;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  padding: var(--spacing-md);
  color: var(--text-primary);
}

.carousel-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  margin-bottom: var(--spacing-xs);
}

.carousel-description {
  font-size: var(--font-size-sm);
  opacity: 0.8;
}

.carousel-dots {
  position: absolute;
  bottom: var(--spacing-sm);
  right: var(--spacing-md);
  display: flex;
  gap: var(--spacing-xs);
}

.carousel-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.carousel-dot.active {
  background-color: var(--primary-color);
}

// 分类导航样式（与UI原型一致，优化显示）
.category-nav {
  display: flex;
  gap: 32rpx; // 使用rpx代替spacing-md
  margin: 0 32rpx 48rpx; // 使用rpx单位
  overflow-x: auto;
  padding-bottom: 16rpx; // 使用rpx代替spacing-sm
  justify-content: flex-start;
}

.category-nav::-webkit-scrollbar {
  height: 8rpx;
}

.category-nav::-webkit-scrollbar-thumb {
  background: var(--border-color);
  border-radius: 4rpx;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 140rpx;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.category-item:active {
  transform: translateY(-4rpx); // -2px in rpx
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: var(--gradient-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx; // 使用rpx代替spacing-xs
}

.category-name {
  font-size: 28rpx; // 增大字体以显示完整
  color: var(--text-secondary);
  text-align: center;
  width: 100%;
}

// Font Awesome 图标样式
.category-icon-fa {
  font-size: 32rpx;
  color: white;
}

.search-icon {
  font-size: 32rpx;
  color: var(--text-muted);
}

.meta-item i {
  font-size: 24rpx;
  color: var(--text-muted);
  margin-right: 8rpx;
}

.more-link i {
  font-size: 24rpx;
  color: var(--primary-color);
}

// 通用区块样式
.recommendation-section,
.hot-section {
  margin: 0 32rpx 48rpx; // 使用rpx单位
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 32rpx; // 使用rpx代替spacing-md
}

.section-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.more-link {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  cursor: pointer;
}

.more-text {
  font-size: var(--font-size-sm);
  color: var(--novel-primary);
}

// 小说卡片样式（与UI原型一致）
.novel-cards {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.novel-card {
  display: flex;
  gap: var(--spacing-md);
  cursor: pointer;
  transition: transform 0.3s ease;
}

.novel-card:active {
  transform: scale(0.98);
}

.novel-cover {
  width: 160rpx; // 80px in rpx
  height: 240rpx; // 120px in rpx
  border-radius: var(--border-radius-sm);
  flex-shrink: 0;
}

.novel-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.novel-main-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.novel-title {
  font-size: var(--font-size-md);
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.novel-author {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-xs);
}

.novel-description {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.novel-meta {
  display: flex;
  gap: var(--spacing-md);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.meta-text {
  font-size: var(--font-size-xs);
  color: var(--text-muted);
}

// 热门网格样式（与UI原型一致，但优化显示）
.novel-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 32rpx; // 使用rpx代替spacing-md
}

.novel-grid-item {
  text-align: center;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.novel-grid-item:active {
  transform: translateY(-8rpx); // -4px in rpx
}

.novel-grid-cover {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
  box-shadow: 0 8rpx 24rpx var(--shadow-color); // 0 4px 12px in rpx
}

.novel-grid-title {
  font-size: 28rpx; // 增大字体以显示完整
  color: var(--text-primary);
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 3; // 增加行数以显示更多文字
  -webkit-box-orient: vertical;
  overflow: hidden;
  padding: 0 8rpx; // 添加左右padding避免文字被截断
  word-break: break-all; // 允许长单词换行
}

// 加载状态样式
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  flex-direction: column;
}

.loading-text {
  font-size: var(--font-size-md);
  color: var(--text-muted);
  margin-top: var(--spacing-md);
}

// 底部间距
.bottom-spacing {
  height: 40rpx;
}
</style>
